package com.jason.campusinn.utils;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.jason.campusinn.CampusInnApp;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

/**
 * HttpUtils 框架封装回调类，
 * 
 * @param <T>
 *            返回值类型
 */
public abstract class HttpRequestCallBack<T> extends RequestCallBack<T> {
	private Dialog mPbar;
	private Context mContext;
	public static final String TAG = "httpUtil";

	public abstract void onSuccessed(ResponseInfo<T> responseInfo);

	public abstract void onFailed(HttpException exception, String reason);

	public HttpRequestCallBack() {
	}

	public HttpRequestCallBack(Context mContext) {
		this.mContext = mContext;
	}

	public HttpRequestCallBack(Context mContext, Dialog mPbar) {
		this.mContext = mContext;
		this.mPbar = mPbar;
	}

	/** 设置显示进度的dialog */
	public void setProgressDialog(Dialog mPbar) {
		this.mPbar = mPbar;
	}

	@Override
	public void onStart() {
		// startTime = System.currentTimeMillis();
		if (!CommonMethodUtils.isNetWorkConnected(CampusInnApp.getInstance())) {
			Toast.makeText(CampusInnApp.getInstance(), "网络未连接，请检查网络设置",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (mPbar != null) {
			mPbar.show();
		}
		super.onStart();
	}

	@Override
	public void onLoading(long total, long current, boolean isUploading) {
		super.onLoading(total, current, isUploading);
	}

	@Override
	public void onCancelled() {
		super.onCancelled();
		if (mPbar != null) {
			mPbar.dismiss();
		}
	}

	@Override
	public void onFailure(HttpException exception, String reason) {
		if (mPbar != null) {
			mPbar.dismiss();
		}
		if (!CommonMethodUtils.isNetWorkConnected(CampusInnApp.getInstance())) {
			reason = "network_no_connect";
		}
		LogUtil.d("failed_reason:" + reason);
		this.onFailed(exception, reason);
	}

	@Override
	public void onSuccess(ResponseInfo<T> responseInfo) {
		if (mPbar != null) {
			mPbar.dismiss();
		}

		if (TextUtils.isEmpty((String) responseInfo.result)) {
			this.onFailed(null, "empty result");
			return;
		}
		this.onSuccessed(responseInfo);
	}
}
